﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;

namespace xmlTranslate
{
    public class GoogleTranslate : ITranslate
    {
        public string Translate(string sourceStr, bool saveSource = true)
        {
            sourceStr = sourceStr.Replace("\r", "").Replace("\n", "").Trim();
            sourceStr = $"({sourceStr})";
            HttpHelper httpHelper = new HttpHelper();
            var request = httpHelper.GetHtml(new HttpItem
            {
                URL = $"http://translate.google.cn/translate_a/single?client=gtx&dt=t&dj=1&ie=UTF-8&sl=auto&tl=zh-CN&q={sourceStr}"
            });



            try
            {
                var res = JsonConvert.DeserializeObject<goRes1>(request.Html);
                string str = res.sentences.Where(p => !string.IsNullOrWhiteSpace(p.trans)).Select(p => p.trans).Distinct().FirstOrDefault();
                if (str != null)
                {
                    if (saveSource)
                        return $"{str}{sourceStr}";
                }
                return sourceStr;
            }
            catch
            {
                return sourceStr;
            }
        }

    }


    public class goRes1
    {

        public List<goResult> sentences { get; set; }
    }
    public class goResult
    {
        public string trans { get; set; }
        public string orig { get; set; }

    }
}
